use async_trait::async_trait;
use clap::Parser;

use crate::commands::commands::Command;
use crate::models::models::command::CommandState;
use crate::utils::command;

#[derive(Debug, Default, Clone, Parser)]
#[clap(disable_help_flag = true)]
struct Args {
    // 是否转大写
    #[arg(short = 's', long = "stringify", default_value_t = false)]
    stringify: bool,
    // JSON字符串
    value: String,
}

#[derive(Debug, Default, Clone)]
pub(crate) struct JsonCommand {}

#[async_trait]
impl Command for JsonCommand {
    async fn execute(&self, command: crate::models::models::command::Command) -> crate::models::models::command::Command {
        let args = command::parse_command_args::<Args>(command.args.as_str());
        if args.is_err() {
            return self.save_command_output(command, CommandState::Success, args.unwrap_err().to_string());
        }

        let args = args.unwrap();
        let value = serde_json::from_str::<serde_json::Value>(args.value.as_str());
        if value.is_err() {
            return self.save_command_output(command, CommandState::Failed, value.unwrap_err().to_string());
        }

        let value = value.unwrap();

        if args.stringify {
            return self.save_command_output(command, CommandState::Success, serde_json::to_string(&value).unwrap());
        }

        self.save_command_output(command, CommandState::Success, serde_json::to_string_pretty(&value).unwrap())
    }
}